<?php

namespace services\user;

use api\modules\mini\forms\user\UserWithdrawAccountForm;
use common\components\Service;
use common\models\user\UserWithdrawAccount;
use Yii;

class UserWithdrawAccountService extends Service
{
    /**
     * 我的提现信息
     * @return array
     */
    public function getMyInfo(): array
    {
        return $this->info(Yii::$app->user->identity->user->withdraw_id);
    }

    /**
     * 账号类型
     * @return array
     */
    public static function getConditionTypes(): array
    {
        $types = UserWithdrawAccount::$types;
        $data = [];
        foreach ($types as $key => $row) {
            $data[] = [
                'value' => $key,
                'label' => $row,
                'is_show_bank' => $key == UserWithdrawAccount::TYPE_BANK ? 1 : 0,
            ];
        }
        return $data;
    }

    public function info(int $id): array
    {
        $userWithdrawAccount = UserWithdrawAccount::findOne($id);
        return [
            'id' => $userWithdrawAccount->id ?? 0,
            'type' => $userWithdrawAccount->type ?? UserWithdrawAccount::TYPE_ALIPAY,
            'card_no' => $userWithdrawAccount->card_no ?? '',
            'name' => $userWithdrawAccount->name ?? '',
            'bank_name' => $userWithdrawAccount->bank_name ?? '',
            'condition' => [
                'type' => self::getConditionTypes()
            ],
        ];
    }

    /**
     * 编辑提现账号
     * @param UserWithdrawAccountForm $model
     * @return void
     * @throws \Exception
     */
    public static function edit(UserWithdrawAccountForm $model): void
    {
        try {
            $transaction = Yii::$app->db->beginTransaction();

            // 1.新增账号
            $userWithdrawAccount = $model->getUserWithdrawAccount();
            if (empty($userWithdrawAccount)) {
                $userWithdrawAccount = new UserWithdrawAccount();
                $userWithdrawAccount->user_id = Yii::$app->user->identity->member_id;
            }
            $userWithdrawAccount->type = $model->type;
            $userWithdrawAccount->card_no = $model->card_no;
            $userWithdrawAccount->name = $model->name;
            $userWithdrawAccount->bank_name = $model->bank_name;
            $userWithdrawAccount->saveAndCheckResult();

            // 2.更新提现账号
            Yii::$app->user->identity->user->withdraw_id = $userWithdrawAccount->id;
            Yii::$app->user->identity->user->saveAndCheckResult();

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }
}